package leetcode101.string_problem;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author Synhard
 * @version 1.0
 * @class leetcode101.graph.Code1
 * @description 242. 有效的字母异位词
 * 给定两个字符串 s 和 t ，编写一个函数来判断 t 是否是 s 的字母异位词。
 *
 * 示例 1:
 *
 * 输入: s = "anagram", t = "nagaram"
 * 输出: true
 * 示例 2:
 *
 * 输入: s = "rat", t = "car"
 * 输出: false
 *
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-05-21 8:40
 */
public class Code1 {
    public static void main(String[] args) {
        String s = "cat";
        String t = "car";
        System.out.println(isAnagram(s, t));
    }

    public static boolean isAnagram(String s, String t) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
        }
        for (int i = 0; i < t.length(); i++) {
            if (map.get(s.charAt(i)) == null) {
                return false;
            } else {
                map.put(t.charAt(i), map.get(t.charAt(i)) - 1);
            }
        }
        Set<Map.Entry<Character, Integer>> set = map.entrySet();
        Iterator<Map.Entry<Character, Integer>> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Character, Integer> temp = iterator.next();
            if (temp.getValue() != 0) {
                return false;
            }
        }
        return true;
    }
}
